<template>
  <div class="kb-container">
    <div class="kb-header">
      <h2 class="kb-title">我的知识库</h2>
      <div class="kb-header-actions">
        <n-input-group class="kb-search-group">
          <n-input
            v-model:value="filterUserId"
            placeholder="按创建人ID筛选..."
            class="kb-search-input"
            clearable
            @input="filterKnowledgeBases"
          />
          <n-button size="medium" @click="filterKnowledgeBases" class="kb-search-btn">
            <template #icon>
              <n-icon><SearchOutline /></n-icon>
            </template>
            搜索
          </n-button>
        </n-input-group>
        <n-button type="primary" size="medium" @click="openAddDialog" class="kb-add-btn">
          <template #icon>
            <n-icon><AddOutline /></n-icon>
          </template>
          新建知识库
        </n-button>
      </div>
    </div>
    
    <div class="kb-content">
      <div v-if="filteredKnowledgeBases.length" class="kb-grid">
        <div
          v-for="kb in filteredKnowledgeBases"
          :key="kb.id"
          :class="['kb-item', kb.status === 1 ? 'kb-item-active' : 'kb-item-inactive']"
          @click="goToDocumentPage(kb.id, kb.name, kb.threshold)"
        >
          <div class="kb-item-header">
            <div class="kb-item-icon">
              <n-icon size="24"><ServerOutline /></n-icon>
            </div>
            <h3 class="kb-item-title">{{ kb.name }}</h3>
          </div>
          <p class="kb-description">{{ kb.description || '暂无描述' }}</p>
          <div class="kb-meta">
            <span class="kb-meta-item">
              <n-icon size="14"><DocumentTextOutline /></n-icon>
              {{ kb.fileCount || 0 }} 文件
            </span>
            <span class="kb-meta-item">
              <n-icon size="14"><TimeOutline /></n-icon>
              {{ formatTime(kb.createTime) }}
            </span>
          </div>
          <div class="kb-actions">
            <n-button class="kb-action-btn kb-action-primary" @click.stop="goToDocumentPage(kb.id, kb.name, kb.threshold)">
              <template #icon>
                <n-icon><ChatbubbleOutline /></n-icon>
              </template>
              对话
            </n-button>
            <n-button class="kb-action-btn kb-action-secondary" @click.stop="handleEditKb(kb)">
              <template #icon>
                <n-icon><CreateOutline /></n-icon>
              </template>
              编辑
            </n-button>
          </div>
        </div>
      </div>
      <n-empty v-else description="暂无知识库" class="kb-empty" />
    </div>
    
    <!-- 新增知识库模态框 -->
    <n-modal v-model:show="addDialogVisible" :mask-closable="false" preset="card" class="kb-modal" style="width: 500px;">
      <template #header>
        <div class="modal-header">
          <n-icon size="20"><ServerOutline /></n-icon>
          <span>新建知识库</span>
        </div>
      </template>
      <n-form :model="addForm" label-placement="left" label-width="100" size="medium" :rules="formRules">
        <n-form-item label="知识库名称" path="name">
          <n-input v-model:value="addForm.name" placeholder="请输入知识库名称" />
        </n-form-item>
        <n-form-item label="创建人ID" path="createUserId">
          <n-input-number v-model:value="addForm.createUserId" placeholder="请输入创建人ID" style="width: 100%" />
        </n-form-item>
        <n-form-item label="知识库描述" path="description">
          <n-input type="textarea" v-model:value="addForm.description" placeholder="请输入知识库描述" :rows="3" />
        </n-form-item>
        <n-form-item label="检索阈值" path="threshold">
          <n-input-number v-model:value="addForm.threshold" :min="0" :max="1" :step="0.01" :precision="2" style="width: 100%" />
        </n-form-item>
        <n-form-item label="状态" path="status">
          <n-switch v-model:value="addForm.status" :checked-value="1" :unchecked-value="0">
            <template #checked>正常</template>
            <template #unchecked>禁用</template>
          </n-switch>
        </n-form-item>
      </n-form>
      <template #footer>
        <div class="modal-footer">
          <n-button @click="addDialogVisible = false">取消</n-button>
          <n-button type="primary" @click="saveKb" :loading="saving">
            <template #icon>
              <n-icon><CheckmarkOutline /></n-icon>
            </template>
            保存
          </n-button>
        </div>
      </template>
    </n-modal>

    <!-- 编辑知识库模态框 -->
    <n-modal v-model:show="editDialogVisible" :mask-closable="false" preset="card" class="kb-modal" style="width: 500px;">
      <template #header>
        <div class="modal-header">
          <n-icon size="20"><SettingsOutline /></n-icon>
          <span>编辑知识库</span>
        </div>
      </template>
      <n-form :model="editForm" label-placement="left" label-width="100" size="medium" :rules="formRules">
        <n-form-item label="知识库ID" path="id">
          <n-input v-model:value="editForm.id" disabled />
        </n-form-item>
        <n-form-item label="知识库名称" path="name">
          <n-input v-model:value="editForm.name" placeholder="请输入知识库名称" />
        </n-form-item>
        <n-form-item label="创建人ID" path="createUserId">
          <n-input-number v-model:value="editForm.createUserId" placeholder="请输入创建人ID" style="width: 100%" />
        </n-form-item>
        <n-form-item label="知识库描述" path="description">
          <n-input type="textarea" v-model:value="editForm.description" placeholder="请输入知识库描述" :rows="3" />
        </n-form-item>
        <n-form-item label="检索阈值" path="threshold">
          <n-input-number v-model:value="editForm.threshold" :min="0" :max="1" :step="0.01" :precision="2" style="width: 100%" />
        </n-form-item>
        <n-form-item label="状态" path="status">
          <n-switch v-model:value="editForm.status" :checked-value="1" :unchecked-value="0">
            <template #checked>正常</template>
            <template #unchecked>禁用</template>
          </n-switch>
        </n-form-item>
      </n-form>
      <template #footer>
        <div class="modal-footer">
          <n-button @click="editDialogVisible = false">取消</n-button>
          <n-button type="primary" @click="saveEditKb" :loading="saving">
            <template #icon>
              <n-icon><CheckmarkOutline /></n-icon>
            </template>
            保存
          </n-button>
        </div>
      </template>
    </n-modal>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive } from 'vue'
import { 
  NButton, NInput, NInputGroup, NIcon, NModal, NForm, NFormItem, NEmpty, 
  NInputNumber, NSwitch, useMessage
} from 'naive-ui'
import { 
  SearchOutline, AddOutline, ServerOutline,
  DocumentTextOutline, TimeOutline, ChatbubbleOutline, 
  SettingsOutline, CheckmarkOutline, CreateOutline
} from '@vicons/ionicons5'
import { aiService } from '../../shared/services/ai-service'
import { useRouter } from 'vue-router'

const router = useRouter()
const message = useMessage()
const knowledgeBases = ref<any[]>([])
const filteredKnowledgeBases = ref<any[]>([])
const filterUserId = ref('')
const addDialogVisible = ref(false)
const editDialogVisible = ref(false)
const saving = ref(false)

// 表单验证规则
const formRules = reactive({
  name: {
    required: true,
    message: '请输入知识库名称',
    trigger: ['input', 'blur']
  } as any,
  createUserId: {
    required: true,
    type: 'number',
    message: '请输入创建人ID',
    trigger: ['input', 'blur']
  } as any
})

const addForm = ref({
  id: '',
  name: '',
  createUserId: null,
  description: '',
  status: 1,
  threshold: 0.7
})

const editForm = ref({
  id: '',
  name: '',
  createUserId: null,
  description: '',
  status: 1,
  threshold: 0.7
})

const pagination = reactive({
  page: 1,
  pageSize: 10,
  itemCount: 0,
  showSizePicker: true,
  pageSizes: [10, 20, 50]
})



function formatTime(val: string) {
  if (!val) return ''
  const d = new Date(val)
  return d.toLocaleString()
}

const loadKnowledgeBases = async () => {
  try {
    const response = await aiService.getAllKnowledgeBases()
    if (response.code === 0) {
      knowledgeBases.value = response.data
      filteredKnowledgeBases.value = response.data
      pagination.itemCount = response.data.length
    } else {
      message.error('获取知识库列表失败: ' + response.msg)
    }
  } catch (error) {
    console.error('获取知识库列表出错:', error);
    message.error('获取知识库列表出错')
  }
}

const filterKnowledgeBases = () => {
  if (!filterUserId.value) {
    filteredKnowledgeBases.value = knowledgeBases.value
  } else {
    filteredKnowledgeBases.value = knowledgeBases.value.filter(kb => 
      kb.createUserId.toString().includes(filterUserId.value)
    )
  }
  pagination.itemCount = filteredKnowledgeBases.value.length
}

const openAddDialog = () => {
  addForm.value = {
    id: '', // 添加id属性
    name: '',
    createUserId: null,
    description: '',
    status: 1,
    threshold: 0.7
  }
  addDialogVisible.value = true
}

const closeAddDialog = () => {
  addDialogVisible.value = false
}

const closeEditDialog = () => {
  editDialogVisible.value = false
}

const saveKnowledgeBase = async (isEdit: boolean) => {
  try {
    saving.value = true
    let response
    
    if (isEdit) {
      response = await aiService.updateKnowledgeBase(editForm.value.id, editForm.value)
    } else {
      response = await aiService.createKnowledgeBase(addForm.value)
    }
    
    if (response.code === 0) {
      message.success(isEdit ? '更新知识库成功' : '创建知识库成功')
      loadKnowledgeBases()
      closeAddDialog()
      closeEditDialog()
    } else {
      message.error(response.msg || (isEdit ? '更新知识库失败' : '创建知识库失败'))
    }
  } catch (error) {
    console.error(`${isEdit ? '更新' : '创建'}知识库出错:`, error);
    message.error(`${isEdit ? '更新' : '创建'}知识库出错`)
  } finally {
    saving.value = false
  }
}

const goToDocumentPage = (id: string, name: string, threshold: number) => {
  router.push({
    path: `/kb/${id}`,
    query: { kbName: name, threshold: threshold.toString() }
  })
}

const handleEditKb = (kb: any) => {
  editForm.value = { ...kb }
  editDialogVisible.value = true
}

const saveKb = async () => {
  await saveKnowledgeBase(false)
}

const saveEditKb = async () => {
  await saveKnowledgeBase(true)
}

onMounted(() => {
  loadKnowledgeBases()
})
</script>

<style scoped>
/* 知识库容器样式 */
.kb-container {
  display: flex;
  flex-direction: column;
  height: 100%;
  background-color: #f8f9fa;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

/* 知识库头部样式 */
.kb-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px 24px;
  background-color: #fff;
  border-bottom: 1px solid #e9ecef;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.05);
}

.kb-title {
  margin: 0;
  font-size: 20px;
  font-weight: 600;
  color: #212529;
}

.kb-header-actions {
  display: flex;
  align-items: center;
  gap: 12px;
}

.kb-search-group {
  width: 300px;
}

.kb-search-input {
  flex: 1;
}

.kb-search-btn {
  border-top-left-radius: 0;
  border-bottom-left-radius: 0;
}

.kb-add-btn {
  display: flex;
  align-items: center;
  gap: 6px;
}

/* 知识库内容区域样式 */
.kb-content {
  flex: 1;
  padding: 24px;
  overflow: auto;
}

.kb-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
  gap: 20px;
}

.kb-item {
  display: flex;
  flex-direction: column;
  padding: 20px;
  background-color: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.08);
  transition: all 0.2s ease;
  cursor: pointer;
}

.kb-item:hover {
  box-shadow: 0 4px 16px rgba(0, 0, 0, 0.12);
  transform: translateY(-2px);
}

.kb-item-active {
  border-left: 4px solid #4285f4;
}

.kb-item-inactive {
  border-left: 4px solid #9e9e9e;
}

.kb-item-header {
  display: flex;
  align-items: center;
  margin-bottom: 12px;
}

.kb-item-icon {
  display: flex;
  align-items: center;
  justify-content: center;
  width: 48px;
  height: 48px;
  margin-right: 16px;
  background-color: #f1f3f4;
  border-radius: 8px;
  color: #5f6368;
}

.kb-item-title {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #202124;
}

.kb-description {
  margin: 0 0 16px;
  font-size: 14px;
  color: #5f6368;
  line-height: 1.5;
  flex: 1;
}

.kb-meta {
  display: flex;
  justify-content: space-between;
  margin-bottom: 16px;
  font-size: 13px;
  color: #5f6368;
}

.kb-meta-item {
  display: flex;
  align-items: center;
  gap: 4px;
}

.kb-actions {
  display: flex;
  gap: 8px;
}

.kb-action-btn {
  flex: 1;
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 6px;
  height: 36px;
  font-size: 14px;
}

.kb-action-primary {
  background-color: #4285f4;
  color: white;
  border: none;
}

.kb-action-primary:hover {
  background-color: #3367d6;
}

.kb-action-secondary {
  background-color: #f1f3f4;
  color: #5f6368;
  border: none;
}

.kb-action-secondary:hover {
  background-color: #e8eaed;
}

.kb-empty {
  margin-top: 60px;
}

/* 模态框样式 */
.kb-modal {
  border-radius: 12px;
}

.modal-header {
  display: flex;
  align-items: center;
  gap: 12px;
  font-size: 18px;
  font-weight: 600;
  color: #212529;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
}

/* 原有样式保留 */
.kb-grid-view {
  margin-top: 16px;
}
.kb-grid-container {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 20px;
  padding: 20px;
  overflow-y: auto;
  max-height: calc(100vh - 200px);
}
.kb-card {
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 16px;
  transition: all 0.2s;
  display: flex;
  flex-direction: column;
  height: 180px;
  width: 100%;
  box-sizing: border-box;
}

.kb-card-active {
  background: linear-gradient(135deg, #f0f9ff 0%, #e0f2fe 100%);
  border-color: #7dd3fc;
}

.kb-card-inactive {
  background: linear-gradient(135deg, #f8fafc 0%, #f1f5f9 100%);
  border-color: #cbd5e1;
}
.kb-card:hover {
  transform: translateY(-2px);
}

.kb-card-active:hover {
  box-shadow: 0 4px 16px rgba(125, 211, 252, 0.3);
}

.kb-card-inactive:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}
.kb-card-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 12px;
  flex-shrink: 0;
}
.kb-card-title {
  font-weight: 600;
  font-size: 16px;
  color: #333;
  flex: 1;
  margin-right: 8px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
.kb-card-actions {
  display: flex;
  gap: 4px;
  flex-shrink: 0;
}
.kb-card-content {
  flex: 1;
  margin-bottom: 8px;
  overflow: hidden;
  display: flex;
  flex-direction: column;
  font-size: 14px;
  color: #666;
  gap: 4px;
}

.status-active {
  color: #18a058;
  font-weight: 500;
}

.status-inactive {
  color: #d03050;
  font-weight: 500;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .kb-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }
  
  .kb-header-actions {
    width: 100%;
    justify-content: flex-end;
  }
  
  .kb-search-group {
    width: 100%;
  }
  
  .kb-grid {
    grid-template-columns: 1fr;
  }
}
</style>
